package it.pir.es03ChatUDP;

import java.io.*;
import java.net.*;

public class Client implements Runnable {

	private String nickname;
	private String address;
	private int port;
	private Message reply;
	private ObjectOutputStream objectOutputStream;
	private ObjectInputStream objectInputStream;
	private ByteArrayOutputStream bos;
	private ByteArrayInputStream bis;
	private DatagramSocket socket;
	private static final int MAX = 3000;
	
	public Client(String nickname, String address, int port) throws UnknownHostException, IOException {
		this.nickname = nickname;
		this.address = address;
		this.port = port;
		connect();
	}
	
	private void connect() throws IOException {
		socket = new DatagramSocket();
		
		//Viene creato un msg di autenticazione da inviare per primo
		Message authentication = new Message(nickname, "", Message.AUTHENTICATION);
		
		bos = new ByteArrayOutputStream();
		
		objectOutputStream = new ObjectOutputStream(bos);
		objectOutputStream.writeObject(authentication);
		objectOutputStream.flush();
		
		byte buffer[] = bos.toByteArray();
		DatagramPacket packet = new DatagramPacket(buffer,buffer.length,InetAddress.getByName(address),port);
		socket.send(packet);
	}
	
	public void sendMessage(Message message) throws IOException {
		
		bos = new ByteArrayOutputStream();
		objectOutputStream = new ObjectOutputStream(bos);
		objectOutputStream.writeObject(message);
		objectOutputStream.flush();
		
		byte buffer[] = bos.toByteArray();
		DatagramPacket packet = new DatagramPacket(buffer,buffer.length,InetAddress.getByName(address),port);
		socket.send(packet);
	}

	public Message getReply() {
		return reply;
	}
	
	@Override
	public void run() {
		
		
		
		try {
			
			/*Alloco un buffer in ricezione*/
			byte[] buffer = new byte[MAX];
			
			/*Creo un pacchetto datagram*/
			DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
			
			
			
			
		
			
			/*Sto in attesa di un eventuale messaggio sullo stream di input*/
			while(true) {
				
				socket.receive(packet);
				
				/*Creo un oggetto ByteArray in input*/
				bis = new ByteArrayInputStream(buffer,0,packet.getLength());
				
				objectInputStream = new ObjectInputStream(bis);
		
				
				
							
				reply=(Message)objectInputStream.readObject();
				System.out.println(reply.getNickname() + ": "+ reply.getMessage());
				
				if(reply.getType()==Message.DISCONNECT){
					System.exit(1);
				}
			}
		} 	
		catch (IOException e) {
			System.out.println("ERRORE! Problemi di comunicazione con il server! Classe Client");
			// Il programma termina perchè il nome utente è già in uso
			System.exit(1);
			
		} catch (ClassNotFoundException e) {
			System.out.println("ERRORE CLIENT! Classe non trovata! ");
		}
		
	}
	
	
}
